import { formatFileSize } from './utils/helpers.js';

export class DOMManager {
  constructor(app) {
    this.app = app;
    this.initElements();
    this.initEventListeners();
    this.loadTheme();
  }

  initElements() {
    this.elements = {
      messageInput: document.getElementById('messageInput'),
      sendBtn: document.getElementById('sendBtn'),
      messages: document.getElementById('messages'),
      userList: document.getElementById('userList'),
      statusDot: document.querySelector('.status-dot'),
      statusText: document.querySelector('.status-text'),
      nicknameModal: document.getElementById('nicknameModal'),
      nicknameInput: document.getElementById('nicknameInput'),
      confirmNickname: document.getElementById('confirmNickname'),
      fileInput: document.createElement('input'),
      uploadBtn: document.getElementById('uploadBtn'),
      themeToggle: document.getElementById('themeToggle'),
      changeNickname: document.getElementById('changeNickname'),
      progressContainer: document.createElement('div'),
      progressBar: document.createElement('div'),
      progressFilename: document.createElement('div'),
      progressStats: document.createElement('div'),
      copyServerAddress: document.getElementById('copyServerAddress')
    };

    this.initFileElements();
    this.validateElements();
  }

  validateElements() {
    if (!this.elements.messageInput || !this.elements.sendBtn ||
      !this.elements.messages || !this.elements.userList) {
      throw new Error('Required DOM elements not found');
    }
  }

  initFileElements() {
    this.elements.fileInput.type = 'file';
    this.elements.fileInput.accept = '*';
    this.elements.fileInput.style.display = 'none';

    this.elements.progressContainer.className = 'progress-container';
    const progressInfo = document.createElement('div');
    progressInfo.className = 'progress-info';

    this.elements.progressFilename.className = 'progress-filename';
    this.elements.progressStats.className = 'progress-stats';

    progressInfo.appendChild(this.elements.progressFilename);
    progressInfo.appendChild(this.elements.progressStats);

    const progressBarContainer = document.createElement('div');
    progressBarContainer.className = 'progress-bar-container';

    this.elements.progressBar.className = 'progress-bar';

    progressBarContainer.appendChild(this.elements.progressBar);
    this.elements.progressContainer.appendChild(progressInfo);
    this.elements.progressContainer.appendChild(progressBarContainer);

    const inputContainer = document.querySelector('.input-container');
    if (inputContainer) {
      inputContainer.appendChild(this.elements.fileInput);
      inputContainer.appendChild(this.elements.progressContainer);
    }
  }

  initEventListeners() {
    this.initThemeToggle();
    this.initMessageSending();
    this.initNicknameHandling();
    this.initFileUpload();
    this.initWindowFocus();
    this.initCopyServerAddress();
  }

  initThemeToggle() {
    if (this.elements.themeToggle) {
      this.elements.themeToggle.addEventListener('click', () => {
        const isDark = document.body.classList.toggle('dark-mode');
        localStorage.setItem('theme', isDark ? 'dark' : 'light');
      });
    }
  }

  loadTheme() {
    const savedTheme = localStorage.getItem('theme') || 'light';
    document.body.classList.toggle('dark-mode', savedTheme === 'dark');
  }

  initMessageSending() {
    this.elements.sendBtn.addEventListener('click', () => this.sendMessage());
    this.elements.messageInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        this.sendMessage();
      }
    });
  }

  initNicknameHandling() {
    this.elements.confirmNickname.addEventListener('click', () => {
      const nickname = this.elements.nicknameInput.value.trim();
      if (!nickname) return;

      if (nickname === this.app.nickname) {
        this.hideNicknameModal();
        return;
      }

      this.app.setNickname(nickname);
      this.hideNicknameModal();

      if (this.app.connectionManager.socket?.readyState === WebSocket.OPEN) {
        this.updateConnectionStatus('connecting');
        this.app.connectionManager.sendMessage({
          type: 'setNickname',
          nickname: nickname
        });
      }
    });

    this.elements.changeNickname.addEventListener('click', () => {
      this.showNicknameModal();
      this.elements.nicknameInput.value = this.app.nickname || '';
    });
  }

  initFileUpload() {
    this.elements.uploadBtn.addEventListener('click', () => {
      this.elements.fileInput.click();
    });

    this.elements.fileInput.addEventListener('change', async (e) => {
      const file = e.target.files[0];
      if (file) {
        await this.app.fileHandler.handleFileUpload(file);
      }
    });
  }

  initWindowFocus() {
    window.addEventListener('focus', () => {
      this.app.messageHandler.resetUnreadCount();
    });
  }

  initCopyServerAddress() {
    fetch('/server-address')
      .then(response => response.json())
      .then(data => {
        const serverAddress = data.address;
        this.elements.copyServerAddress.addEventListener('click', () => {
          navigator.clipboard.writeText(serverAddress).then(() => {
            alert(`${serverAddress}服务器地址已复制到剪贴板！`);
          }).catch(err => {
            console.error('复制失败:', err);
            alert('复制失败，请手动复制。');
          });
        });
      })
      .catch(err => {
        console.error('获取服务器地址失败:', err);
        alert('获取服务器地址失败，请手动复制。');
      });
  }

  showNicknameModal() {
    this.elements.nicknameModal.style.display = 'flex';
  }

  hideNicknameModal() {
    this.elements.nicknameModal.style.display = 'none';
  }

  updateConnectionStatus(status) {
    const statusMap = {
      connecting: { text: '连接中...', color: 'var(--warning-color)' },
      connected: { text: '已连接', color: 'var(--success-color)' },
      disconnected: { text: '未连接', color: 'var(--error-color)' },
      error: { text: '连接错误', color: 'var(--error-color)' }
    };

    this.elements.statusDot.style.backgroundColor = statusMap[status].color;
    this.elements.statusText.textContent = statusMap[status].text;
  }

  showProgress(filename, totalSize) {
    this.elements.progressContainer.style.display = 'block';
    this.elements.progressBar.style.width = '0%';
    this.elements.progressFilename.textContent = filename;
    this.elements.progressStats.textContent = `0% (0/${formatFileSize(totalSize)})`;
  }

  hideProgress() {
    this.elements.progressContainer.style.opacity = '0';
    setTimeout(() => {
      this.elements.progressContainer.style.display = 'none';
      this.elements.progressContainer.style.opacity = '1';
    }, 300);
  }

  updateProgress(loaded, total, percent) {
    const rounded = Math.round(percent);
    this.elements.progressBar.style.width = `${rounded}%`;
    this.elements.progressStats.textContent =
      `${rounded}% (${formatFileSize(loaded)}/${formatFileSize(total)})`;
  }

  updateProgressStatus(status) {
    this.elements.progressStats.textContent = status;
  }

  scrollToBottom() {
    this.elements.messages.scrollTop = this.elements.messages.scrollHeight;
  }

  sendMessage() {
    const message = this.elements.messageInput.value.trim();
    if (message) {
      this.app.connectionManager.sendMessage({
        type: 'message',
        message: message
      });
      this.elements.messageInput.value = '';
      this.elements.messageInput.style.height = 'auto';
    }
  }
} 